$import('meta.metaHelper');
var fieldTypeMap=(function getFieldTypeMap(){
	var jsonObj=[{"CODE":"1","NAME":"varchar","TEXT":"字符串"}
	,{"CODE":"12","NAME":"text","TEXT":"文本"}
	,{"CODE":"-5","NAME":"bigint","TEXT":"长整型"}
	,{"CODE":"4",NAME:"integer","TEXT":"整型"}
	,{"CODE":"6",NAME:"float","TEXT":"浮点型"}
	,{"CODE":"16",NAME:"float","TEXT":"布尔型"}
	,{"CODE":"8",NAME:"double","TEXT":"双精度型"}
	,{"CODE":"3",NAME:"decimal","TEXT":"货币型"}
	,{"CODE":"91",NAME:"date","TEXT":"日期型"}
	,{"CODE":"92",NAME:"time","TEXT":"钟点型"}
	,{"CODE":"93",NAME:"timestamp","TEXT":"时间戳"}
	,{"CODE":"2000",NAME:"object","TEXT":"对象"},
	{CODE:"2003",NAME:"array","TEXT":"数组"}
	];
	var map={};
	Ext.each(jsonObj,function(n,i){
		map[n["CODE"]]=n["TEXT"];
	});
	return map;
})();

function initSchemaGrid(region){
	var selModel=new Ext.grid.RowSelectionModel({singleSelect : false});
	
	var column= new Ext.grid.ColumnModel({
        columns: [
        		{ header: '序号', dataIndex: 'SEQ'},
				{ header: 'ID', dataIndex: 'ID', sortable: true ,hidden:true },
				{ header: '模型ID', dataIndex: 'FID', hidden:true},
				{ header: '名称', dataIndex: 'NAME'},
				{ header: '编码', dataIndex: 'CODE'},
				{ header: '说明', dataIndex: 'TEXT'},
				{ header: '类型', dataIndex: 'TYPE',renderer:function(v){
					return fieldTypeMap[v];
				}}
        ]
    });
	  
	var store=new Ext.data.JsonStore({
		fields:['ID','FID','SEQ','NAME','CODE','TEXT','TYPE'],
		autoLoad:true,
		proxy:new Ext.data.RestProxy({url:'./../model/fields'}),
		idProperty:"ID",
		root:"itemList",
		totalProperty: 'pageInfo.total',
		baseParams:{id:id,"pageInfo.start":0,"pageInfo.limit":20,"pageInfo.cache":0,"pageInfo.total":20,"sortInfo.field":"TABLE_NAME","sortInfo.direct":"asc"},
		paramNames:{start:'pageInfo.start',limit:'pageInfo.limit',sort:'sortInfo.field',dir:'sortInfo.direct'},
		sortInfo:{
			field : "SEQ",
			direction : "ASC"
		}
	});
	  var tbars = new Ext.Toolbar({items: [
		  
		  {text:"选择字段",iconCls:"icon-create",handler:function(){
			  
		  }},
		  {text:"修改",iconCls:"icon-modify",handler:function(){
			  
		  }},
		  
		  {text:"删除",iconCls:"icon-delete",handler:function(){
			  
		  }},
		  {text:"刷新",iconCls:"icon-finish",handler:function(){
			  store.reload();
		  }},
		  {text:'导入',iconCls:"icon-finish",handler:function(){
			  
		  }},
		  {text:"导出",iconCls:"icon-finish",hander:function(){
			  
		  }}
	                          	  ]});
	  var conf = {xtype:'paging',pageSize:20,displayInfo:true,autoWidth:true};
      conf.autoWidth=true;
      conf.displayMsg='<font color="red">{0}~{1}</font>条,总数: <font color="red">{2}</font> 条.';
      conf.emptyMsg= "数据记录为空";
      conf.store=store;
	  var grid= new Ext.grid.EditorGridPanel({
          tbar:tbars,
          id:'schema_grid',
          split:true,
          height:380,
          store: store,
          region:region,
          selModel:selModel,
          colModel: column,
          bbar:Ext.create(conf),
          viewConfig:{forceFit:true}
      });
	  return grid;
}


var booleanStore=new Ext.data.ArrayStore({
    fields: [
	            'SID',
	            'TEXT'
	        ],
	        data: [
	            [true, 'true'],
             [false, 'false']
         ]	
});

function initAttrPropPanel(region){
	var attrFieldMetaId=100060140265;
	var list=metaHelper.getSchema(attrFieldMetaId);
	var propertyNames={},source={},customEditors={};
	Ext.each(list,function(n,i){
		var key=n["name"];
		propertyNames[key]=n["text"];
		source[key]='';
		if(n["picker"]){
			customEditors[key]=new Ext.grid.GridEditor(new Ext.form.TriggerField({selectOnFocus:true,triggerClass: 'x-form-search-trigger',triggerClick:function(){
				
			}}));
		}else if(n["type"]==16){
			customEditors[key]=new Ext.grid.GridEditor(new Ext.form.ComboBox({typeAhead:true, triggerAction:'all', mode: 'local',store:booleanStore,valueField:"SID",displayField:"TEXT"}));
		}else if(n["type"]==1){
			customEditors[key]=new Ext.grid.GridEditor(new Ext.form.TextField());
		}else if(n["type"]==97){
			customEditors[key]=new Ext.grid.GridEditor(new Ext.form.DateField());
		}else{
			customEditors[key]=new Ext.grid.GridEditor(new Ext.form.NumberField());
		}
	});
	var tbar=[{text:'保存属性',iconCls:'icon-submit',handler:function(){
		var grid=Ext.getCmp('dict_grid');
		var cur_row=grid["cur_row"];
		if(!cur_row)return;
		var attrGrid=Ext.getCmp('attrGrid');
		var source2=attrGrid.getSource();
		var metaId=metaHelper.getMetaIdByName('pack.model.dict.field');
		var params={};
		var ov=Ext.getCmp('attrGrid').originalValue;
		var source1=attrGrid["source"];
		for(var i in source2){
			if(source2[i]!=ov[i])
				params[i]=source2[i];
		}
		var sid=cur_row.get("id");
		metaHelper.saveAttrMap(metaId,sid,params,function(){
			Ext.getCmp('attrGrid').loadData();
			Ext.Msg.alert('提示','保存成功');
		});
		}},{text:'刷新',iconCls:'icon-reload',handler:function(){
			Ext.getCmp('attrGrid').loadData();
		}}];
	var propsGrid = new Ext.grid.PropertyGrid({
        width: 400,
        tbar:tbar,
        autoSort:false,
        id:"attrGrid",
        clicksToEdit:1,
        split:true,
        customEditors:customEditors,
        region:region,
        propertyNames: propertyNames,
        source: source,
        viewConfig : {
            forceFit: true
        },
        listners:{
        	'cellclick' : function(grid, rowIndex, columnIndex, e) {  
        	    return true;
        	}  
        }
    });
	propsGrid.loadData=function(id){
		if(!id){
			var grid=Ext.getCmp('dict_grid');
			var cur_row=grid["cur_row"];
			if(cur_row==null)return;
			id=cur_row.get("SID");
		}
		if(id<=0)return;
		metaHelper.getAttrMap(metaId,id,function(rs){
			if(!rs["success"])return Ext.Msg.alert('提示','加载属性配置出错');
			var data=rs["data"]||{};
			Ext.applyIf(data,source);
			for(var i in data){
				if(data[i]==null){
					data[i]="";
				}
			}
			propsGrid["source"]=data;
			propsGrid.setSource(data);
			propsGrid.originalValue={};
			Ext.apply(propsGrid.originalValue,data);
		});
		
	};
	propsGrid.setAutoScroll(true);
	return propsGrid;
}

function initMarkForm(region){
	var markMetaId=3001103002;
	var form = new Ext.FormPanel({
        frame: true,
        layout: {
            type:'vbox',
            padding:'5',
            align:'stretch'
        },
        defaults:{margins:'0 0 5 0'},
        region:region,
        id:'markForm',
        closable:true,
        split:true,
        waitMsgTarget: true,
        tbar:[{
            text:'保存备注',
            iconCls:"icon-submit",
            handler:function(){
            	 var form=Ext.getCmp('markForm').getForm();
             	var row=Ext.getCmp('dict_grid')["cur_row"];
             	if(!row)return TopExt.Msg.alert('提示','请先选择字段');
             	var sid=row.get("SID");
             	var markCtrl=form.findField("mark");
             	var mark=markCtrl.getValue();
             	if(mark!=markCtrl.originalValue){
             		
             	}else{
             		return Ext.Msg.alert('提示','没有修改,无需提交');
             	}
            }},{
            	text:'刷新',
            	iconCls:"icon-reload",
            	handler:function(){
            		form["loadData"]();
            	}
            }],
        items: [
                {
                	name:'mark',
                	flex:1,
                	align:'stretchmax',
                	xtype:'htmleditor'
                }]
 });
	form["loadData"]=function(dictId){
		if(!dictId){
			dictId=form["dictId"];
		}else{
			form["dictId"]=dictId;
		}
		
	};
	return form;
}

Ext.onReady(function(){
	Ext.QuickTips.init();
	var fieldGrid=initSchemaGrid('center');
	new Ext.Viewport({
        width: 900,
        layout:"border",
		split:true,
        items:[fieldGrid]
	});
});
